package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.SysFoodMapper;
import com.mars.module.admin.mapper.SysWarehouseMapper;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysFoodTransferRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysFoodTransferMapper;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysFoodTransferService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 粮食转仓记录业务层处理
 *
 * @author mars
 * @date 2024-04-02
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFoodTransferServiceImpl implements ISysFoodTransferService {

    private final SysFoodTransferMapper baseMapper;
    private final SysFoodMapper foodMapper;
    private final SysWarehouseMapper warehouseMapper;
    private final SysUserMapper userMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFoodTransfer add(SysFoodTransferRequest request) {
        SysFood sysFood = foodMapper.selectById(request.getFoodId());
        if (sysFood.getHouseId() == request.getNewHouseId()) {
            throw new ServiceException("转移后仓库不能和转移前仓库一样！");
        }
        SysFoodTransfer entity = SysFoodTransfer.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        String serialNo = getSerialNo("ZC");
        entity.setAmount(sysFood.getAmount());
        entity.setOldHouseId(sysFood.getHouseId());
        entity.setSerialNo(serialNo);
        baseMapper.insert(entity);
        sysFood.setHouseId(request.getNewHouseId());
        foodMapper.updateById(sysFood);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    private String getSerialNo(String prefix) {
        return prefix + System.currentTimeMillis();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysFoodTransferRequest request) {
        SysFoodTransfer entity = SysFoodTransfer.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysFoodTransfer getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysFoodTransfer> pageList(SysFoodTransferRequest request) {
        Page<SysFoodTransfer> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysFoodTransfer> query = this.buildWrapper(request);
        IPage<SysFoodTransfer> pageRecord = baseMapper.selectPage(page, query);
        List<SysFoodTransfer> records = pageRecord.getRecords();
        List<SysFoodTransfer> recordsNew = new ArrayList<>();
        for (SysFoodTransfer collection : records) {
            SysFood sysFood = foodMapper.selectById(collection.getFoodId());
            SysWarehouse oldHouse = warehouseMapper.selectById(collection.getOldHouseId());
            SysWarehouse newHouse = warehouseMapper.selectById(collection.getNewHouseId());
            SysUser sysUser = userMapper.selectById(collection.getCreateById());
            collection.setOldHouseName(oldHouse == null ? "" : oldHouse.getName());
            collection.setNewHouseName(newHouse == null ? "" : newHouse.getName());
            collection.setFoodName(sysFood == null ? "" : sysFood.getName());
            collection.setCreateByName(sysUser.getUserName());
            recordsNew.add(collection);
        }
        if (StringUtils.isNotBlank(request.getFoodName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getFoodName().contains(request.getFoodName())).collect(Collectors.toList());
        }
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysFoodTransfer> list(SysFoodTransferRequest request) {
        LambdaQueryWrapper<SysFoodTransfer> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysFoodTransfer> buildWrapper(SysFoodTransferRequest param) {
        LambdaQueryWrapper<SysFoodTransfer> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSerialNo())) {
            query.like(SysFoodTransfer::getSerialNo, param.getSerialNo());
        }
        return query;
    }

}
